package org.hilo.boot.core.logback;

import java.io.PrintStream;

import ch.qos.logback.core.status.OnConsoleStatusListener;

/**
 * 可继承该类，然后重载 doInit() 方法
 * @author zollty
 * @since 2016年8月26日
 */
public class EnvInitStatusListener extends OnConsoleStatusListener {

    private volatile boolean init;

    @Override
    protected PrintStream getPrintStream() {
        if (!init) {
            init = true;
            super.getPrintStream().println("Init log var....................................................");
            doInit();
        }
        return super.getPrintStream();
    }
    
    /**
     * 该方法不要抛出任何异常
     */
    protected void doInit() {
        initConfig();
    }
    
    /**
     * 初始化配置
     */
    private void initConfig() {
        // PatternLayout.defaultConverterMap.put("m", SensitiveDataConverter.class.getName());
        // PatternLayout.defaultConverterMap.put("msg", SensitiveDataConverter.class.getName());
        // PatternLayout.defaultConverterMap.put("message", SensitiveDataConverter.class.getName());
        // ~ 读取环境相关的配置
        String placeholderName = "spring.profiles.active";
        String propVal = System.getProperty(placeholderName);
        if (propVal == null) {
            // Fall back to searching the system environment.
            propVal = System.getenv(placeholderName);
        }
        if (propVal != null) {
            if (propVal.indexOf("dev") > -1) {
                System.setProperty("deploy.env", "dev");
            } else {
                String envName = propVal.split(",")[0].trim();
                System.setProperty("deploy.env", envName);
            }
        }
    }

}
